package yun.web.springmvc.ext;

import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class MvcResultBeanReturnValueHandler implements HandlerMethodReturnValueHandler {

    // 返回false, 则尝试下一个 returnValueHandler
    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        return true;
    }

    // supportsReturnType 返回true, 执行此处
    @Override
    public void handleReturnValue(Object obj, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
        if (obj != null) {
            HttpServletRequest req = (HttpServletRequest) webRequest.getNativeRequest();
            HttpServletResponse resp = (HttpServletResponse) webRequest.getNativeResponse();
            MvcWriteUtil.write(req, resp, obj);
        }
        // 标记为已经处理完毕
        mavContainer.setRequestHandled(true);
    }
}
